#include "error.h"
namespace errlog {
	ErrorCtr* ErrorCtr::_i = 0;
	ErrorCtr::ErrorCtr():
	_iLogLevel(maxverbose){
}
ErrorCtr::~ErrorCtr() {
	for (loggertype::iterator i = _vLogger.begin(); i != _vLogger.end(); ++i) {//tell it to all loggers
		delete *i;
	}
}
void ErrorCtr::message(std::string file, int line, std::string s, std::string sFunc, LogLevel l) {
	if (l>=getLogLevel()) { //if is to be logged
		bool bL = false;
		for (loggertype::iterator i = _vLogger.begin(); i != _vLogger.end(); ++i) {//tell it to all loggers
			(*i)->log(file,line,s,sFunc,l);
			bL = true;
		}
		if (!bL)
			std::cout <<ErrorCtr::getLogLevelName(l)<<" ("<<file<<":"<<line<<" "<<sFunc<<"): "<<s<< std::endl;
	}
}
std::string ErrorCtr::getLogLevelName(LogLevel l) {
	switch (l) {
		case maxverbose: return 	"MAXVERBOSE";
		case verbose: return 	"VERBOSE";
		case warning: return 	"WARNING";
		case error: return 	"ERROR";
		case critical: return 	"CRITICAL";
	}
	return	"UNKNOWN";
}
ErrorCtr* ErrorCtr::getInstance() { //Singleton
	if (ErrorCtr::_i == 0)
		ErrorCtr::_i = new ErrorCtr();
	return ErrorCtr::_i;
}
void ErrorCtr::setLogLevel(LogLevel i) {
	_iLogLevel = i;
	std::ostringstream s;
	s<<"Loglevel set to "<<i;
	VERBOSE(s.str());
}
LogLevel ErrorCtr::getLogLevel() const {return _iLogLevel;}
void ErrorCtr::addLogger(Logger* l) { //add new logger
	_vLogger.push_back(l);
}

/* class PrintLogger */
PrintLogger::PrintLogger() {}
PrintLogger::~PrintLogger() {}
void PrintLogger::log(std::string file, int line, std::string s, std::string sFunc, LogLevel l) {
	std::cout <<ErrorCtr::getLogLevelName(l)<<" ("<<file<<":"<<line<<" "<<sFunc<<"): "<<s<< std::endl;
}
/* class FileLogger */
FileLogger::FileLogger(std::string f) {
	_fLog.open(f.c_str());
	if (_fLog.is_open())
		_bLog = true;
	else {
		_bLog = false;
		WARNING("logger unable to open file "+f);
	}
}
FileLogger::~FileLogger() {
	_fLog.close();
}
void FileLogger::log(std::string file, int line, std::string s, std::string sFunc, LogLevel l) {
	if (_bLog)
		_fLog <<ErrorCtr::getLogLevelName(l)<<" ("<<file<<":"<<line<<" "<<sFunc<<"): "<<s<< std::endl;
}
DialogLogger::DialogLogger() {}
DialogLogger::~DialogLogger() {}
void DialogLogger::log(std::string file, int line, std::string s, std::string sFunc, LogLevel l) {
	std::ostringstream st;
	st	<< s << std::endl
			<< std::endl
			<< "More informations:"<<std::endl
			<< file << " (" << line <<")" << std:: endl
			<< sFunc;
	QMessageBox::warning(0,
		QString(ErrorCtr::getLogLevelName(l).c_str()),
		QString(st.str().c_str()),
		QMessageBox::Ok,QMessageBox::NoButton);
}
/* class logger */
Logger::Logger() {}
Logger::~Logger() {}
}
